// Olivia.cpp : Defines the entry point for the application.
//

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>

#include "OgreFramework.h"
#include "wx/event.h"
#include "wxlua/wxlua.h"
#include "wxlua/wxlua_bind.h"
#include "wxbind/include/wxbinddefs.h"
#include "wxbind/include/wxbase_bind.h"
#include "wxbind/include/wxcore_bind.h"
#include "wx/msw/app.h"
#include "ogrebinding.h"
#include "Olivia.h"

// WinMain comes from here
IMPLEMENT_APP(OliviaEditor)

OliviaEditor::OliviaEditor() : m_framework(0)
{}

OliviaEditor::~OliviaEditor() 
{
	Clean();
}

bool OliviaEditor::OnInit()
{
	m_framework = new OgreFramework();
	const char *title = "OliviaEditor";
	if (!m_framework->initOgre(title))
	{
		return false;
	}

	wxLuaBinding_wxlua_init();
	wxLuaBinding_wxbase_init();
	wxLuaBinding_wxcore_init();
	lua_State *lua = OgreFramework::getSingleton().m_lua;
	m_wx_state = wxLuaState(lua, wxLUASTATE_SETSTATE | wxLUASTATE_STATICSTATE);
	if (!m_wx_state.Ok())
	{
		return false;
	}
	m_wx_state.RegisterBindings();
	if (!m_framework->ScriptMain())
	{
		return false;
	}
	return true;
}

void OliviaEditor::Clean()
{
	if (m_wx_state.IsOk())
	{
		m_wx_state.CloseLuaState(true);
		m_wx_state.Destroy();
	}

	wxSafeYield();

	if (m_framework)
	{
		delete m_framework;
		m_framework = NULL;
	}
}

int OliviaEditor::OnExit()
{
	Clean();
	return wxApp::OnExit();
}

bool OliviaEditor::ProcessIdle()
{
	fflush(stdout);
	return wxApp::ProcessIdle();
}